import tensorflow as tf
from captcha_func import *

# 定义CNN
def crack_captcha_cnn(FLAGS,CHAR_SET_LEN,w_alpha=0.1, b_alpha=0.1):
    x = tf.reshape(X, shape=[-1, FLAGS.img_height, FLAGS.img_width, 1])

    # 3 conv layer
    w_c1 = tf.Variable(w_alpha * tf.random_normal([3, 3, 1, 32]))
    b_c1 = tf.Variable(b_alpha * tf.random_normal([32]))
    conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x, w_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    #conv1 = tf.nn.dropout(conv1, keep_prob)

    w_c2 = tf.Variable(w_alpha * tf.random_normal([3, 3, 32, 64]))
    b_c2 = tf.Variable(b_alpha * tf.random_normal([64]))
    conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, w_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    #conv2 = tf.nn.dropout(conv2, keep_prob)

    w_c3 = tf.Variable(w_alpha * tf.random_normal([3, 3, 64, 64]))
    b_c3 = tf.Variable(b_alpha * tf.random_normal([64]))
    conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, w_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))
    conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
    #conv3 = tf.nn.dropout(conv3, keep_prob)

    # Fully connected layer
    # 获取conv3的shape
    conv3_shape=conv3.get_shape().as_list()
    w_d = tf.Variable(w_alpha * tf.random_normal([conv3_shape[1]*conv3_shape[2]*conv3_shape[3], 2048]))
    b_d = tf.Variable(b_alpha * tf.random_normal([2048]))
    dense = tf.reshape(conv3, [-1, w_d.get_shape().as_list()[0]])
    dense = tf.nn.relu(tf.add(tf.matmul(dense, w_d), b_d))
    dense = tf.nn.dropout(dense, keep_prob)
    
    w_d_2 = tf.Variable(w_alpha * tf.random_normal([2048, 512]))
    b_d_2 = tf.Variable(b_alpha * tf.random_normal([512]))
    dense_2 = tf.nn.relu(tf.add(tf.matmul(dense, w_d_2), b_d_2))
    dense_2 = tf.nn.dropout(dense_2, keep_prob)

    w_out = tf.Variable(w_alpha * tf.random_normal([512, FLAGS.captcha_len * CHAR_SET_LEN]))
    b_out = tf.Variable(b_alpha * tf.random_normal([FLAGS.captcha_len * CHAR_SET_LEN]))
    out = tf.add(tf.matmul(dense_2, w_out), b_out,name='out')
    return out



# 训练
def train_crack_captcha_cnn(FLAGS,CHAR_SET_LEN):
    #CNN 训练过程
    output = crack_captcha_cnn(FLAGS,CHAR_SET_LEN)
    #损失函数
    loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=Y),name='loss')
    learning_rate=0.01
    global_step=tf.Variable(0,trainable=False)
    lr=tf.train.exponential_decay(learning_rate, global_step, 1000, 0.96, staircase=True,name='learning_rate')
    #Adam函数
    optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss,global_step,name='optimizer')
    #转换矩阵形状
    predict = tf.reshape(output, [-1, MAX_CAPTCHA, CHAR_SET_LEN])
    max_idx_p = tf.argmax(predict, 2)
    max_idx_l = tf.argmax(tf.reshape(Y, [-1, MAX_CAPTCHA, CHAR_SET_LEN]), 2)
    #相等的判断
    correct_pred = tf.equal(max_idx_p, max_idx_l)
    accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32),name='accuracy')

    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        ckpt = tf.train.get_checkpoint_state('captcha_model')
        if ckpt and ckpt.model_checkpoint_path:
            checkpoint_path = ckpt.model_checkpoint_path
            saver.restore(sess, checkpoint_path)
        step = 0
        while True:
            batch_x, batch_y = get_next_batch(32)
            sess.run(optimizer, feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.85})


            # 每10 step计算一次准确率
            if step % 100 == 0:
                saver.save(sess, "captcha_model/crack_capcha.model")
                batch_x_test, batch_y_test = get_next_batch(64)
                acc,loss_ = sess.run([accuracy, loss], feed_dict={X: batch_x_test, Y: batch_y_test, keep_prob: 1.})
                print(step, loss_)
                print(step, acc)
                print('*'*100)
                # 如果准确率大于75%,保存模型,完成训练
                if acc > 0.99:
                    #持久化
                    saver.save(sess, "captcha_model/crack_capcha.model")
                    break

            step += 1


if __name__ == '__main__':
    # 命令行参数
    # 验证码图片宽度
    tf.app.flags.DEFINE_integer('img_width',IMAGE_WIDTH,'Image Width')
    # 验证码图片高度
    tf.app.flags.DEFINE_integer('img_height',IMAGE_HEIGHT,'Image Height')
    # 验证码文本长度
    tf.app.flags.DEFINE_integer('captcha_len',MAX_CAPTCHA,'captcha text length')
    # 验证码来源数据集，1为纯数字，2为数字加小写字母，3为数字加小写字母加大写字母
    tf.app.flags.DEFINE_integer('choice ',3,'Choice char set，1 is only number，2 is Pure numbers plus lowercase letters，3 or other is all')
    FLAGS = tf.app.flags.FLAGS

    img_width =FLAGS.img_width
    img_height = FLAGS.img_height
    captcha_len = FLAGS.captcha_len
    choice = FLAGS.choice
    if choice==1:
        char_set = number
    elif choice==2:
        char_set = number+alphabet
    else:
        char_set = number + alphabet + ALPHABET
    CHAR_SET_LEN = len(char_set)
    #生成验证码值和图片
    text, image = gen_captcha_text_and_image(char_set,img_width,img_height)
    print("验证码图像channel:", image.shape)  # (60, 160, 3)
    print("验证码文本最长字符数", MAX_CAPTCHA)

    X = tf.placeholder(tf.float32, [None, img_height * img_width],name='X')
    Y = tf.placeholder(tf.float32, [None, captcha_len * CHAR_SET_LEN],name='Y')
    keep_prob = tf.placeholder(tf.float32,name='keep_prob')  # dropout
    train_crack_captcha_cnn(FLAGS,CHAR_SET_LEN)
